package com.boarsoft.boar.deploy.plan.biz;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.agent.AgentService;
import com.boarsoft.boar.deploy.entity.BuildPlan;
import com.boarsoft.boar.deploy.entity.BuildPlanItem;
import com.boarsoft.boar.deploy.entity.BuildPlanDetail;
import com.boarsoft.boar.deploy.plan.PlanBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.flow.exchange.FlowExchanger;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("planBiz")
public class PlanBizImpl extends SimpleBizImpl implements PlanBiz {

	@Autowired
	@Lazy
	@Qualifier("agentC")
	private AgentService agentC;
	@Autowired
	@Qualifier("localFlowExchanger")
	private FlowExchanger flowExchanger;

	@Override
	@Transactional(readOnly = true)
	public PagedResult<BuildPlan> list(String projId, String key, String orderBy, int pageNo, int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(BuildPlan.class.getName());
		sb.append(" d where 1=1");
		if (Util.strIsNotEmpty(projId)) {
			sb.append(" and d.projId='").append(projId).append("'");
		}
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (d.code like '%").append(key);
			sb.append("%' or d.name like '%").append(key);
			sb.append("%')");
		}
		int total = dao.getTotal("select count(d.id)".concat(sb.toString()));
		//
		if (Util.strIsNotEmpty(orderBy)) {
			sb.append(" order by d.").append(orderBy);
		} else {
			sb.append(" order by d.id");
		}
		List<BuildPlan> lt = dao.list("select d".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<BuildPlan>(total, lt, pageNo, pageSize);
	}

	@Override
	@Transactional
	public void save(BuildPlan o) {
		if (Util.strIsEmpty(o.getId())) {
			dao.save(o);
		} else {
			dao.merge(o);
		}
	}

	/**
	 * 删除某个部署计划，需同步删除其关联的部署详情表（build_plan_detail）信息
	 * hibernate根据mapping文件配置自动删除子表数据
	 */
	@Override
	@Transactional
	public void delete(String id) {
		StringBuilder sb = new StringBuilder();
		// 通过planId删除PlanServer
		sb.setLength(0);
		sb.append("delete from ").append(BuildPlanDetail.class.getName())//
				.append(" where planId=:id");
		dao.createQuery(sb.toString()).setParameter("id", id).executeUpdate();
		// 通过planId删除明细
		sb.setLength(0);
		sb.append("delete from ").append(BuildPlanItem.class.getName())//
				.append(" where planId=:id");
		dao.createQuery(sb.toString()).setParameter("id", id).executeUpdate();
		// 删除部署计划
		dao.delete(BuildPlan.class, id);
	}

	@Override
	@Transactional
	public void update(BuildPlan o) {
		dao.merge(o);
	}

	@Override
	@Transactional(readOnly = true)
	public BuildPlan get(String id) {
		return (BuildPlan) dao.get(BuildPlan.class, id);
	}

	@Override
	@Transactional
	public boolean start(String id) {
		BuildPlan o = this.get(id);
		o.setStatus(BuildPlan.STATUS_READY);
		return true;
	}

	@Override
	@Transactional
	public boolean stop(String id) {
		BuildPlan o = this.get(id);
		o.setStatus(BuildPlan.STATUS_NOUSE);
		return true;
	}

	// private boolean copyFileLocal(String srcParent, String dynPath, String
	// targetPath, String aimParent) {
	// boolean isSuc = false;
	// try {
	// if (Util.strIsNotEmpty(dynPath)) {
	// srcParent = srcParent.concat(File.separator).concat(dynPath);
	// aimParent = aimParent.concat(File.separator).concat(dynPath);
	// }
	// String rpcAddr =
	// DeployConfig.COMPILE_SERVER_ADDRESS.concat(":").concat(DeployConfig.RPC_COMM_PORT);
	// RpcContext.specify2(rpcAddr);
	// String args[] = { srcParent, targetPath, aimParent, targetPath, null };
	// ReplyInfo<String> reply = agentC.executeCmd(BuildKey.LOCAL_COPY, args,
	// null);
	// if (reply.isSuccess()) {
	// isSuc = true;
	// }
	// } finally {
	// RpcContext.specify2(null);
	// }
	// return isSuc;
	//
	// }
	//
	// /**
	// * 远程文件拷贝 - 从远程拷贝到本地
	// *
	// * @param srcParent
	// * @param dynPath
	// * @param targetPath
	// * @param aimParent
	// * @return
	// */
	// private boolean copyFileRemote(String rmtHost, String rmtUser, String
	// srcParent, String dynPath, String targetPath,
	// String aimParent) {
	// boolean isSuc = false;
	// try {
	// if (Util.strIsNotEmpty(dynPath)) {
	// srcParent = srcParent.concat(File.separator).concat(dynPath);
	// aimParent = aimParent.concat(File.separator).concat(dynPath);
	// }
	// String rpcAddr =
	// DeployConfig.COMPILE_SERVER_ADDRESS.concat(":").concat(DeployConfig.RPC_COMM_PORT);
	// RpcContext.specify2(rpcAddr);
	// String args[] = { srcParent, targetPath, BuildKey.SOURCE_FILE_NOZIP,
	// rmtHost, aimParent, targetPath, rmtUser,
	// BuildKey.RCP_FROM_REMOTE };
	// ReplyInfo<String> reply = agentC.executeCmd(BuildKey.REMOTE_COPY, args,
	// null);
	// if (reply.isSuccess()) {
	// isSuc = true;
	// }
	// } finally {
	// RpcContext.specify2(null);
	// }
	// return isSuc;
	// }
}